//
//  ClickTextView.m
//  merchant
//
//  Created by 吕清毅 on 2018/3/12.
//  Copyright © 2018年 ehome. All rights reserved.
//

#import "ClickTextView.h"

@implementation ClickTextView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setEditable:NO];
        // 必须实现 ScrollView 禁止滚动才行
        [self setScrollEnabled:NO];
    }
    return self;
}

- (void)setText:(NSString *)text
{
    [super setText:text];
    self.content = [[NSMutableAttributedString alloc]initWithString:text];
    [self.content addAttribute:NSAttachmentAttributeName value:self.font range:NSMakeRange(0, text.length)];
    if (self.textColor) {
        [self.content addAttribute:NSForegroundColorAttributeName value:self.textColor range:NSMakeRange(0, text.length)];
    }
    
}

- (void)setUnderLineTextViewWithRange:(NSRange)underlineTextRange withUnderLineColor:(UIColor *)color andWithCoverColor:(UIColor *)coverColor withBlock:(clickTextViewParkBlock )block
{
    if (self.text.length < underlineTextRange.location + underlineTextRange.length) {
        return;
    }
    //设置行间距

    NSMutableParagraphStyle *descStyle = [[NSMutableParagraphStyle alloc]init];
    [descStyle setAlignment:NSTextAlignmentCenter];//行间距
    [self.content addAttribute:NSParagraphStyleAttributeName value:descStyle range:NSMakeRange(0, self.content.length)];
    //设置下划线
    [self.content addAttribute:NSUnderlineStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleNone] range:underlineTextRange];
    //设置文字颜色
    if (color) {
        [self.content addAttribute:NSForegroundColorAttributeName value:color range:underlineTextRange];
    }
    self.attributedText = self.content;
    
    //设置下划线的点击事件
    self.selectedRange = underlineTextRange;
    
    //获取选中范围内的矩形框
    NSArray *selectionRects = [self selectionRectsForRange:self.selectedTextRange];
    
    //清空选中范围
    self.selectedRange = NSMakeRange(0, 0);
    //可能会点击的范围数组
    NSMutableArray *selectArray = [[NSMutableArray alloc]init];
    
    for (UITextSelectionRect *selectionRect in selectionRects) {
        CGRect rect = selectionRect.rect;
        if (rect.size.width == 0 || rect.size.height == 0) {
            continue;
        }
        // 将有用的信息打包<存放到字典中>存储到数组中
        NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
        // 存储文字对应的frame，一段文字可能会有两个甚至多个frame，考虑到文字换行问题
        [dic setObject:[NSValue valueWithCGRect:rect] forKey:@"rect"];
        // 存储下划线对应的文字
        [dic setObject:[self.text substringWithRange:underlineTextRange] forKey:@"content"];
        // 存储相应的回调的block
        [dic setObject:block forKey:@"block"];
        // 存储对应的点击效果背景颜色
        [dic setValue:coverColor forKey:@"coverColor"];
        [selectArray addObject:dic];
    }
    //将可能点击的范围数组存在大数组
    [self.rectsArray addObject:selectArray];
}


- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [touches anyObject];
    
    CGPoint point = [touch locationInView:self];
    //通过触摸点查询是不是点击下划线的地方
    NSArray *selectArray = [self touchingSpacialWithPoint:point];
    
    for (NSDictionary *dict in selectArray) {
        
        if (dict && dict[@"coverColor"]) {
            
            UIView *cover = [[UIView alloc]init];
            cover.backgroundColor = dict[@"coverColor"];
            cover.frame = [dict[@"rect"] CGRectValue];
            cover.layer.cornerRadius = 5;
            cover.tag = kCoverViewTag;
            [self insertSubview:cover atIndex:0];
        }
    }
    
    if (selectArray.count) {
        
        // 如果说有点击效果的话，加个延时，展示下点击效果,如果没有点击效果的话，直接回调
        NSDictionary *dict = [selectArray firstObject];
        clickTextViewParkBlock block = dict[@"block"];
        if (dict[@"coverColor"]) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
              
                block(dict[@"content"]);
            });
        }else
        {
            block(dict[@"content"]);
        }
    }
}


- (NSArray *)touchingSpacialWithPoint:(CGPoint)point
{
    //从所有特殊范围中招待点击的那个点
    for (NSArray *selectArray in self.rectsArray) {
        
        for (NSDictionary *dict in selectArray) {
            
            CGRect myRect = [dict[@"rect"]CGRectValue];
            if (CGRectContainsPoint(myRect, point)) {
                
                return selectArray;
            }
        }
    }
    return nil;
}

//点击结束的时候
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       
        for (UIView *view in self.subviews) {
            
            if (view.tag == kCoverViewTag) {
                [view removeFromSuperview];
            }
        }
    });
}

//取消点击的时候，清除相关的阴影
- (void)touchesCancelled:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    for (UIView *view in self.subviews) {
        
        if (view.tag == kCoverViewTag) {
            [view removeFromSuperview];
        }
    }
}

- (NSMutableArray *)rectsArray
{
    if (_rectsArray == nil) {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        _rectsArray = array;
    }
    return _rectsArray;
}

#pragma mark -- 获取昨天、今天、明天此时的时间
- (void)getTimeAboutTodayAndTorrmowAndYesterday
{
    //1.获取当前时间 零时区的时间
    NSDate *date = [NSDate date];
    NSLog(@"当前零时区时间 %@", date);
    
    //2.获得本地时间 东八区 晚八个小时 以秒计时
    NSDate *date1 = [NSDate dateWithTimeIntervalSinceNow:8 * 60 * 60];
    NSLog(@"今天此时的时间 %@",date1);
    
    //3.昨天此时的时间
    NSDate *yesterdayDate = [NSDate dateWithTimeIntervalSinceNow:(-24 + 8) * 60 * 60];
    NSLog(@"昨天此时的时间 %@",yesterdayDate);
    
    //4.明天此刻
    NSDate *tomorrowDate = [NSDate dateWithTimeInterval:24 * 60 * 60 sinceDate:date1];
    NSLog(@"明天此刻的时间 %@",tomorrowDate);
    
    //5.NSTimeInterval 时间间隔(单位是秒),double 的 typedef
    
    //昨天此时与明天此刻的时间间隔
    NSTimeInterval timeInterval = [tomorrowDate timeIntervalSinceDate:yesterdayDate];
    NSLog(@"昨日和明天此刻的时间(秒) %.0f",timeInterval);
}

#pragma mark -- 获取时间戳(0时区转为时间戳)
- (void)getTimeStamp
{
    //说白了就是看看某个0时区的NSDate和1970.1.1的时间差秒数就好了
    NSDate *date = [NSDate date];
    NSTimeInterval timeIn = [date timeIntervalSince1970];
    NSLog(@"1970年1月1日0时0分0秒至今相差 %.0f 秒", timeIn);
}

#pragma mark -- NSString -> NSDate
/*
 1.先获取一个时间的字符串
 2.严格按照字符串中的时间格式，给dateFormat设置样式
 3.获得的是一个少了8小时的NSDate
 4.手动给NSDate添加8小时，最后得到了一个北京时间的NSDate对象
 5.原因，系统默认字符串是东八区的，但是转化NSDate，他要搞成0时区的！
 */
- (void)stringTransToNSDate
{
    //系统会认为字符串是东八区的时间, 转乘NSDate是零时区的
    NSString *dateStr = @"2016年8月24日 11时05分23秒";
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy年MM月dd日 hh时mm分ss秒"];
    NSDate *date = [dateFormatter dateFromString:dateStr];
    //将转换回来的对象手动加上8小时，回到北京时间
    NSDate *date2 = [date dateByAddingTimeInterval:8 * 60 * 60];
    NSLog(@"字符串转date: %@",date2);
}

/**
 *  将0时区的时间转成0时区的时间戳
 */
+ (NSString *)transformToTimestampWithDate:(NSDate *)date{
    NSTimeInterval inter = [date timeIntervalSince1970];
    return [NSString stringWithFormat:@"%ld", (long)inter];
}

/**
 *  将0时区的时间戳转成0时区的时间
 */
+ (NSDate *)transformToDateWithTimestamp:(NSString *)timestamp{
    NSTimeInterval inter = [timestamp doubleValue];
    NSDate * date = [NSDate dateWithTimeIntervalSince1970:inter];
    return date;
}

/**
 *  将0时区的时间戳转成8时区的时间文本格式（“2015-12-13 13：34：45”）
 */
+ (NSString *)transformToStringWithTimestamp:(NSString *)timestamp{
    //1.先将时间戳->NSDate
    NSDate *date = [self transformToDateWithTimestamp:timestamp];
    //2.将date->NSString
    return [[self transformToStringWithDate:date] substringToIndex:16];
}

/**
 *  将0时区的时间戳(10位数)转成8时区的时间文本格式（“2012-12-12 12：12”）,带有只有时分的
 */
+ (NSString *)transformToHourMiniteFormatWithTimestamp:(NSString *)timestamp{
    //1.先将时间戳->NSDate
    NSDate *date = [self transformToDateWithTimestamp:timestamp];
    //2.将date->NSString
    return [[self transformToStringWithDate:date] substringToIndex:13];
}

/**
 *  将8时区的时间文本格式（“2015-12-13 13：34：45”）转成 0时区的时间戳
 */
+ (NSString *)transformToTimestampWithString:(NSString *)string{
    //1.先将NSString->NSDate
    NSDate *date = [self transformToDateWithString:string];
    //2.将date->timestamp
    return [self transformToStringWithDate:date];
}

/**
 *  将8时区的时间文本格式（“2015-12-13 13：34：45”）转成 0时区的NSDate
 */
+ (NSDate *)transformToDateWithString:(NSString *)string{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale currentLocale]];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [df dateFromString:string];
    return date;
}

/**
 *  将0时区的NSDate转成 8时区的时间文本格式（“2015-12-13 13：34：45”）
 */
+ (NSString *)transformToStringWithDate:(NSDate *)date{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setLocale:[NSLocale currentLocale]];
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *string = [df stringFromDate:date];
    return string;
}
@end
